<template>
  <div class="xuncha-admin">
    <div class="content-wrapper">
      <!-- 左侧统计卡片 -->
      <div class="left-panel">
        <a-spin :spinning="dataListLoading">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-card class="stat-card">
                <div class="card-content">
                  <div class="title">
                    <a-icon type="arrow-up" class="red-icon" />
                    总上报案件
                  </div>
                  <div class="number">{{ dataList.allCaseCount }}</div>
                  <div class="desc">截至目前总数据</div>
                </div>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card class="stat-card">
                <div class="card-content">
                  <div class="title">
                    <a-icon type="eye" class="blue-icon" />
                    总跟踪案件
                  </div>
                  <div class="number">{{ dataList.allDocCount }}</div>
                  <div class="desc">截至目前总数据</div>
                </div>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card class="stat-card">
                <div class="card-content">
                  <div class="title">
                    <a-icon type="clock-circle" class="blue-icon" />
                    总归档案件
                  </div>
                  <div class="number">{{ dataList.allOverCount }}</div>
                  <div class="desc">截至目前总数据</div>
                </div>
              </a-card>
            </a-col>
          </a-row>
        </a-spin>
        
      </div>

      <!-- 右侧数据统计面板 -->
      <div class="right-panel">
        <a-card class="data-panel">
          <div class="panel-header">
            <div class="tabs">
              <a-radio-group
                v-model="currentTab"
                button-style="solid"
                @change="handleTabChange"
              >
                <a-radio-button value="DAY">今日数据</a-radio-button>
                <a-radio-button value="MONTH">本月数据</a-radio-button>
                <a-radio-button value="YEAR">本年数据</a-radio-button>
              </a-radio-group>
            </div>
            <a-range-picker
              style="width: 200px"
              v-model="dateRange"
              :placeholder="['开始日期', '结束日期']"
              valueFormat="YYYY-MM-DD"
              @change="onChange"
            />
          </div>

          <a-spin :spinning="spinning">
            <a-row :gutter="16" class="stat-numbers">
              <a-col :span="5">
                <div class="stat-item">
                  <div class="value">{{ statisticsData.allDocCount || 0 }}</div>
                  <div class="label">审核案件数</div>
                </div>
              </a-col>
              <a-col :span="5">
                <div class="stat-item">
                  <div class="value">
                    {{ statisticsData.newCaseCount || 0 }}
                  </div>
                  <div class="label">新增案件数</div>
                </div>
              </a-col>
              <a-col :span="5">
                <div class="stat-item">
                  <div class="value">
                    {{ statisticsData.newOverCount || 0 }}
                  </div>
                  <div class="label">新上报案件数</div>
                </div>
              </a-col>
              <a-col :span="5">
                <div class="stat-item">
                  <div class="value">{{ statisticsData.overCount || 0 }}</div>
                  <div class="label">结案数</div>
                </div>
              </a-col>
              <a-col :span="4">
                <div class="stat-item">
                  <div class="value">{{ statisticsData.overPecent || 0 }}%</div>
                  <div class="label">结案比率</div>
                </div>
              </a-col>
            </a-row>
          </a-spin>
        </a-card>
      </div>
    </div>
    <div class="shujukanban">
        <!-- <a-spin :spinning="shijianKSpinning"> -->
        <div style="margin-bottom:24px;fontSize:12px;">
            选择查询时间范围 
            <a-range-picker
                style="width: 330px"
                v-model="timeDate"
                :placeholder="['开始日期', '结束日期']"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                :show-time="{ 
                    defaultValue: [
                        moment('00:00:00', 'HH:mm:ss'),  // 开始时间默认00:00
                        moment('23:59:59', 'HH:mm:ss')   // 结束时间默认23:59
                    ]
                }"
                @ok="okTime"
                />
            <!-- <a-range-picker 
                v-model:value="timeDate" 
                :placeholder="['开始日期', '结束日期']"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss" 
                style="margin-left: 20px" 
                @change="okTime" 
                :show-time="{ 
                defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),  // 开始时间默认00:00
                    moment('23:59:59', 'HH:mm:ss')   // 结束时间默认23:59
                ]}"
            /> -->
        </div>
        <div class="pie-style">
          <div class="pie-height" id="ecchartCaseGroupDept"></div>
          <div class="pie-height" id="ecchartCaseGroupBySource"></div>
          <div class="pie-height" id="ecchartCaseGroupByUser"></div>
        </div>
        
        
            
        <!-- </a-spin> -->
    </div>
    <div class="shujukanban">
      
      <div class="data-style">
          <div class="item">
              <div class="title">问题类型分布</div>
              <div v-for="item in QuestionGroup" :key="index" class="q-list">
                  <div class="list-title">
                      <div>{{item.name}}</div>
                      <div>{{item.count}}（{{item.value}}%）</div>
                  </div>
                  <a-progress :percent="item.value" :size="[300, 20]" style="margin-top: 14rpx;"/>
              </div>
          </div>
          <div class="item" >
              <div class="pie-height" id="ecchartCaseGroupByMonth"></div>
              <div class="title" style="margin-top:60px;">全区部门上报事件统计</div>
              <div v-for="item in dataDeptReport" wx:key="index" class="t-list">
                  <div style="width: 30%;"><span class="yuan"></span>已上报</div>
                  <div style="width: 60%;">{{item.name}}</div>
                  <div style="width: 10%;">{{item.count}}</div>
              </div>
          </div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from "dayjs";
import moment from 'moment';

export default {
  name: "XunchaAdmin",
  data() {
    return {
      currentTab: "DAY",
      queryData: {
        startTime: dayjs().format("YYYY-MM-DD"),
        endTime: dayjs().format("YYYY-MM-DD"),
        // interval: "DAY",
      },
      dataList: {},
      statisticsData: {},
      spinning: false,
      dataListLoading: false,
      shijianKSpinning: true,// 数据看板：全区部门办理事件统计
      startTime:'',
      endTime:'',
      timeDate:[ '2024-02-01 00:00:00','2025-3-19 23:59:59'],//dayjs().format("YYYY-MM-DD HH:mm:ss")
      QuestionGroup:[],
      dataDeptReport:[],
    };
  },
  computed: {
    dateRange() {
      return [this.queryData.startTime, this.queryData.endTime];
    },
  },
  mounted() {
      
    this.getQuery();
    this.getData();
    this.getCaseGroupDept();//全区部门办理事件统计
    this.getCaseGroupBySource();//问题来源统计
    this.getCaseGroupByUser();//上报部门统计
    this.getCaseGroupByMonth();//上报部门统计
    
    this.getConmentQuestionGroup();//问题类型分布
    this.getCaseGroupDeptReport();//全区部门上报事件统计
    
  },
  methods: {
    moment,
    onChange(val) {
      this.queryData.startTime = val[0];
      this.queryData.endTime = val[1];
      this.getData();
    },
    handleTabChange(val) {
      let type = val.target.value;
      this.queryData.interval = type;

      // 根据选择的类型设置日期范围
      switch (type) {
        case "DAY": // 今日
          this.queryData.startTime = dayjs().format("YYYY-MM-DD");
          this.queryData.endTime = dayjs().format("YYYY-MM-DD");
          break;
        case "MONTH": // 本月
          this.queryData.startTime = dayjs()
            .startOf("month")
            .format("YYYY-MM-DD");
          this.queryData.endTime = dayjs().endOf("month").format("YYYY-MM-DD");
          break;
        case "YEAR": // 本年
          this.queryData.startTime = dayjs()
            .startOf("year")
            .format("YYYY-MM-DD");
          this.queryData.endTime = dayjs().endOf("year").format("YYYY-MM-DD");
          break;
      }

      this.getData();
    },
    // 统计
    getQuery() {
      this.dataListLoading = true;
      this.$axios
        .post("/government-platform-center/case/getCaseCount")
        .then((res) => {
          if (res.data.code === 0) {
            this.dataList = res.data.data;
          }
        })
        .finally(() => {
          this.dataListLoading = false;
        });
    },
    // 今日、本月、本年
    getData() {
      this.spinning = true;
      const params = new URLSearchParams();
      for (const key in this.queryData) {
        params.append(key, this.queryData[key]);
      }
      this.$axios
        .post("/government-platform-center/case/getCaseCountSum", params)
        .then((res) => {
          this.statisticsData = res.data.data;
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    // 数据看板 全区部门办理事件统计：leader/getCaseGroupDept
    getCaseGroupDept() {
         // 加载统计图
        var chartDom = document.getElementById('ecchartCaseGroupDept');
        var myChart = echarts.init(chartDom);
    
        let api = '/government-platform-center/leader/getCaseGroupDept';//
        this.$axios 
        .post(api,
        // {
        //     current: 50,
        //     offset:1,
        //     startTime:this.startTime,
        //     endTime:this.endTime
        // },    
        )
        .then((res) => {
            //   this.statisticsData = res.data.data;
            let data_this = []
                // console.log('data_this',res)

            if(res.data.msg == 'success'){
                res.data.data.map(v=>{
                    if(v.dept_name && v.count){
                        data_this.push( { name: v.dept_name, value: v.count } )
                    }
                });
                
                console.log('data_this',data_this)
                var option = {
                    title: {
                        text: '全区部门办理事件统计',
                        textStyle:{
                            fontSize: '14px'
                        }
                    },
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        right: '40px',
                        top: '11%',
                        textStyle : {
                        fontSize:'10px'},
                        itemWidth:5, //图列宽度
                        itemHeight:5, //图列宽度
                        formatter:  function(name) {
                        var dataItem = data_this.find(item => item.name === name);
                            // 拼接 name 和 value
                        return dataItem ? dataItem.name + '   ' + dataItem.value + '%' : name; // 如果找不到数据项，则只返回 name
                        },
                    },
                    series: [
                        {
                            name: '暂无数据',
                            type: 'pie',
                            // width: 200,
                            radius: ['40%', '60%'],
                            center:[100,160],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderColor: '#fff',
                                borderWidth: 0
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            labelLine: { show: false },
                            data: data_this
                        }
                    ]
                };
                myChart.setOption(option);
                
            }
           
           
          
        })
        .finally(() => {
            this.shijianKSpinning = false;
        });


        // 窗口变化时自适应
      window.addEventListener('resize', () => {
        myChart.resize();
      });
      
      // 组件销毁时销毁图表
      this.$once('hook:beforeDestroy', () => {
        myChart.dispose();
      });

    },
    // 事件统计 问题来源统计：ecchartCaseGroupBySource
    getCaseGroupBySource() {
        // 加载统计图
        var chartDom = document.getElementById('ecchartCaseGroupBySource');
        var myChart = echarts.init(chartDom);
        console.log(this.timeDate)
        let api = '/government-platform-center/leader/getCaseGroupBySource';//
        this.$axios
        .post(api, 
        {
            current: 50,
            offset:1,
            startTime: this.timeDate[0],
            endTime: this.timeDate[1]
        },{ headers: { "Content-Type": "application/x-www-form-urlencoded"}})
        .then((res) => {
            let data_this = []
            if(res.data.msg == 'success'){
                res.data.data.map(v=>{
                    if(v.time && v.count){
                        data_this.push( { name: v.time, value: v.count } )
                    }
                });
                console.log('问题来源统计',data_this)
                var option = {
                    title: {
                        text: '问题来源统计',
                        textStyle:{
                            fontSize: '14px'
                        }
                    },
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        right: 0,
                        top: '10%',
                        textStyle : {
                        fontSize:'10px',
                        },
                        itemWidth:5, //图列宽度
                        itemHeight:5, //图列宽度
                        formatter:  function(name) {
                        var dataItem = data_this.find(item => item.name === name);
                            // 拼接 name 和 value
                        return dataItem ? dataItem.name + '   ' + dataItem.value + '%' : name; // 如果找不到数据项，则只返回 name
                        },
                    },
                    series: [
                        {
                            name: '暂无数据',
                            type: 'pie',
                            // width: 200,
                            radius: ['40%', '60%'],
                            center:[100,150],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderColor: '#fff',
                                borderWidth: 0
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            labelLine: { show: false },
                            data: data_this
                        }
                    ]
                };
                myChart.setOption(option);
                
            }
           
           
          
        })
        .finally(() => {
            this.shijianKSpinning = false;
        });


        // 窗口变化时自适应
      window.addEventListener('resize', () => {
        myChart.resize();
      });
      
      // 组件销毁时销毁图表
      this.$once('hook:beforeDestroy', () => {
        myChart.dispose();
      });

    },
    // 上报部门统计
    getCaseGroupByUser() {
        // 加载统计图
        var chartDom = document.getElementById('ecchartCaseGroupByUser');
        var myChart = echarts.init(chartDom);
        console.log(this.timeDate)
        let api = '/government-platform-center/leader/getCaseGroupByUser';//
        this.$axios
        .post(api, 
        {
            current: 50,
            offset:1,
            startTime: this.timeDate[0],
            endTime: this.timeDate[1]
        },{ headers: { "Content-Type": "application/x-www-form-urlencoded"}})
        .then((res) => {
            if(res.data.msg == 'success'){
                let data_this = []
                res.data.data.map(v=>{
                    if(v.deptName && v.count){
                        data_this.push( { name: v.deptName, value: v.count } )
                    }
                });
                console.log('上报部门统计',data_this)
                var option = {
                    title: {
                        text: '上报部门统计',
                        textStyle:{
                            fontSize: '14px'
                        }
                    },
                    backgroundColor: "#ffffff",
                    legend: {
                    bottom: '0px',
                    left: 'center',
                    itemHeight: 4,
                    itemWidth: 4,
                    itemStyle: { // 重点修改这里
                        borderRadius: '50%', // 设置为色块高度的一半（假设高度是 15px）
                        borderWidth: 0 // 去掉边框
                    },
                    textStyle : {
                        fontSize: 12,
                    }
                    },
                    series: [{
                        name: '暂无数据',
                        label: {
                            fontSize:8,
                            formatter: '{d}%  {b|{b}}',
                            rich: {
                            b: {
                                color: '#4C5058',
                                fontSize: 8,
                                fontWeight: 'bold',
                                lineHeight: 33
                            },
                            per: {
                                color: '#000',
                                // backgroundColor: '#4C5058',
                                padding: [3, 4],
                                borderRadius: 4
                            }
                            }
                        },
                        type: 'pie',
                        center:[160,150],
                        radius: ['30%', '40%'],
                        data:data_this
                    }]
                };
                myChart.setOption(option); 
            }
        })
        .finally(() => {
            this.shijianKSpinning = false;
        });


        // 窗口变化时自适应
      window.addEventListener('resize', () => {
        myChart.resize();
      });
      
      // 组件销毁时销毁图表
      this.$once('hook:beforeDestroy', () => {
        myChart.dispose();
      });

    },
    // 月度受理
    getCaseGroupByMonth() {
        // 加载统计图
        var chartDom = document.getElementById('ecchartCaseGroupByMonth');
        var myChart = echarts.init(chartDom);
        let api = '/government-platform-center/leader/getCaseGroupByMonth';//
        this.$axios
        .post(api, 
        {
            current: 50,
            offset:1,
            startTime: this.timeDate[0],
            endTime: this.timeDate[1]
        },{ headers: { "Content-Type": "application/x-www-form-urlencoded"}})
        .then((res) => {
            let data_this = []
            if(res.data.msg == 'success'){
                res.data.data.map(v=>{
                    if(v.time && v.count){
                        data_this.push( { name: v.time, value: v.count } )
                    }
                });
                
                const valueList0 = data_this.map(function (item) {
                    return item.name;
                });
                const valueList1 = data_this.map(function (item) {
                    return item.value;
                });

                console.log('全区月度受理',valueList0)
                console.log('全区月度受理',valueList1)
                const option = {
                    title: {
                        text: '全区月度受理',
                        textStyle:{ fontSize: '14px' }
                    },
                    xAxis: {
                        data: valueList0,
                    },
                    yAxis: {
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        color: '#999'
                    }
                    },
                    dataZoom: [
                        {
                        type: 'inside'
                        }
                    ],
                    series: [
                        {
                            name: '暂无数据',
                            type: 'bar',
                            barWidth: 10, // 建议固定柱子宽度
                            // showBackground: true,
                            itemStyle: {
                                borderRadius: [5, 5, 0, 0],// 参数顺序：[左上, 右上, 右下, 左下]
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#FF605E' },
                                { offset: 0.5, color: '#FFF57D' },
                                { offset: 1, color: '#fff' }
                                ])
                            },
                            data: valueList1
                        }
                    ]
            
                };
                myChart.setOption(option); 
            }
        })
        .finally(() => {
            this.shijianKSpinning = false;
        });


        // 窗口变化时自适应
      window.addEventListener('resize', () => {
        myChart.resize();
      });
      
      // 组件销毁时销毁图表
      this.$once('hook:beforeDestroy', () => {
        myChart.dispose();
      });

    },
    // 事件选择
    okTime(date,time){
        this.timeDate = date;
        this.getCaseGroupDept();//全区部门办理事件统计
        this.getCaseGroupBySource();//问题来源统计
        this.getCaseGroupByUser();//上报部门统计
        this.getCaseGroupByMonth();//上报部门统计
        this.getConmentQuestionGroup();//问题类型
        
    },
    getConmentQuestionGroup(){
        let api = '/government-platform-center/leader/getCaseGroupByQuestion';//
        this.$axios
        .post(api, 
        {
            current: 50,
            offset:1,
            startTime: this.timeDate[0],
            endTime: this.timeDate[1]
        },{ headers: { "Content-Type": "application/x-www-form-urlencoded"}})
        .then((res) => {
            let data_this = [];
            if(res.data.msg == 'success'){
                let data_this = [];
                let num =  res.data.data.map((n, i) => n.count +  res.data.data[i].count);
                let nums = num.reduce((sum, n) => sum + n, 0)
                res.data.data.map(v=>{
                    data_this.push( { name: v.time, value:((v.count / nums) * 100).toFixed(2), count:v.count  } )
                })
                this.QuestionGroup = data_this;
                
            }
            
        });
    },
    getCaseGroupDeptReport(){
        let api = '/government-platform-center/leader/getCaseGroupDeptReport';//
        this.$axios
        .post(api, 
        {},{ headers: { "Content-Type": "application/x-www-form-urlencoded"}})
        .then((res) => {
            let data_this = [];
            if(res.data.msg == 'success'){
                let data_this = [];
                res.data.data.map(v=>{
                    if(v.deptName && v.count){
                        data_this.push( { name: v.deptName, count: v.count  } )
                    }
                })
                this.dataDeptReport = data_this;
            }
            
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.xuncha-admin {
  padding: 24px;
  height: 100%;

  .content-wrapper {
    display: flex;
    gap: 24px;
    // height: 100%;
    height: 166px;
    border-radius: 8px;
    .left-panel,
    .right-panel {
      flex: 1;
      min-width: 0; // 防止flex子项溢出
    }

    .left-panel {
      .ant-card {
        height: 100%;
        border-radius: 8px;
      }
    }

    .right-panel {
      .data-panel {
        height: 166px;
        border-radius: 8px;
      }
    }
  }

  .stat-card {
      height: 166px;
    .card-content {
      height: 100%;
      box-sizing: border-box;

      .title {
        font-size: 14px;
        color: #000;
        margin-bottom: 16px;

        .red-icon {
          color: #ff4d4f;
          margin-right: 8px;
        }

        .blue-icon {
          color: #0052d9;
          margin-right: 8px;
        }
      }

      .number {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .desc {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
      }
    }
    
  }

  .data-panel {
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
    }

    .stat-numbers {
      .stat-item {
        text-align: center;

        .value {
          font-size: 24px;
          font-weight: bold;
          color: #0052d9;
          margin-bottom: 8px;
        }

        .label {
          font-size: 12px;
          // color: rgba(0, 0, 0, 0.65);
          color: #000;
        }
      }
    }
  }
  // 1200小屏
  .shujukanban{
    border-radius: 8px;
    background-color: #ffffff;
    margin: 20px 0;
    padding: 24px;
    /* 大屏PC */
    // @media (min-width: 1200px) {
    //     .pie-style{
    //         display: flex;
    //         flex-wrap: wrap;
    //         gap: 15px;
    //         .pie-height{
    //             width: 30%;
    //             height: 300px;
    //              /* 基础宽度 + 弹性增长 */
    //             // flex: 1 1 350px; /* [grow] [shrink] [basis] */
    //             min-width: 350px; /* 防止内容过小时过度收缩 */
    //         }
            
    //     }
    // }
    
       
  
    // @media (min-width: 1600px) {
        
    // }
    .pie-style{
        display: flex;
        align-items: center;
        flex-direction: row;
        justify-content: space-between;
        flex-wrap: nowrap;
        gap:'none';
        .pie-height{
            width: 360px!important;
            height: 300px;
            margin: 0 10px;
        }
    }
       
    .data-style{
        display: flex;
        // align-items: center;
        justify-content: space-between;
        align-items: flex-start;
        height: fit-content;
        margin-top: 60px; 
        .item{
            width: 50%;
            height: 1005;

            .title{
                font-size: 14px; 
                padding-left: 6px;
            }
        }
        .q-list{
            width: 80%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            margin: 7px 0;
        }
        .q-list .list-title{
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 400;
            font-size: 10px;
            color: #333333;
        }
        .t-list{
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-weight: 400;
            font-size: 11px;
            color: #333333;
        }
        .t-list div{
            width: 33.33%;
            margin: 7px;
            display: flex;
            justify-content: left;
            align-items: center;
        }
        .t-list .yuan{
            width: 8px;
            height: 8px;
            background: #4285F5;
            border: 2px solid rgba(105, 141, 255, 0.30);
            border-radius: 50%;
            margin-right: 20px;
        }
        .pie-height{
            width: 100%;
            height: 300px;
            // margin: 0 10px;
        }
    }
  }
}
::v-deep .ant-card-body{
    height: 166px;
    border-radius: 8px;
    
    .card-content{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
}

</style>
